const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderId: '',
    qrcode: '',
    total_fee: 0,
    // 支付结果1成功,0失败
    payStatus: 0,
    haveResult: false,
    count: 60
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let { orderId, qrcode, total_fee } = options; 
    this.setData({
      orderId,
      qrcode,
      total_fee
    })
    this.loop();
    this.getPayResult();
  },

  // 轮询30秒,30秒不成功就算失败
  loop() {
    let timer = setInterval(() => {
      this.setData({ count: --this.data.count });
      // 30秒倒计时结束
      if (this.data.count === 0) {
        clearInterval(timer);
      }
    }, 1000);
  },

  // 查询支付结果
  getPayResult() {
    let url = '/order/payResult';
    let orderId = this.data.orderId;
    const requestTask = app.get(url, { orderId }).then(res => {
      // 1. 有支付结果,没有支付结果,就继续轮询
      if (res.result.haveResult) {
        // 01 为成功,00为失败
        let title = res.result.payStatus === '01' ? '成功' : '失败';
        wx.showModal({
          title: '温馨提示',
          content: '支付'+title,
          success(res2) {
            if (res2.confirm) {
              wx.navigateTo({
                url: '/pages/order/detail/detail?orderId=' + orderId,
              })
            }
          }
        })
        return false;
      }

      // 2. 没有支付结果,并且倒计时还没结束就继续轮询
      if (this.data.count > 0) {
        setTimeout(() => {
          this.getPayResult();
        }, 1000);
        return false;
      }

      // 3. 倒计时结束,还没有结果就直接失败
      wx.showModal({
        title: '温馨提示',
        content: '支付失败',
        success: (res3) => {
          wx.navigateTo({
            url: '/pages/order/detail/detail?orderId=' + orderId,
          })
        }
      });
    })
  }
});
